package artid.com.arttogo.view.photo;

import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

import artid.com.arttogo.R;
import artid.com.arttogo.app.ArtToGoApp;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;


public class ImageDetailFragment extends Fragment {
	private String mImageUrl;
	private ImageView mImageView;
	private ProgressBar progressBar;
	private PhotoViewAttacher mAttacher;
	private View v;
	public static ImageDetailFragment newInstance(String imageUrl) {
		final ImageDetailFragment f = new ImageDetailFragment();

		final Bundle args = new Bundle();
		args.putString("url", imageUrl);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageUrl = getArguments() != null ? getArguments().getString("url")
				: null;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
							 Bundle savedInstanceState) {
		v = inflater.inflate(R.layout.image_detail_fragment,
				container, false);
		mImageView = (ImageView) v.findViewById(R.id.image);
		mAttacher = new PhotoViewAttacher(mImageView);

		mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {

			@Override
			public void onPhotoTap(View arg0, float arg1, float arg2) {
				getActivity().finish();
			}
		});

		progressBar = (ProgressBar) v.findViewById(R.id.loading);
		return v;
	}

	/**
	 * 防止控件没加载出来报空
	 */
	private void getDatas(){
		if(v!=null){
			getData();
		}else{
			new Handler().postDelayed(new Runnable() {

				@Override
				public void run() {
					if(v!=null){
						getDatas();
					}
				}
			}, 1000);
		}
	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		// TODO Auto-generated method stub
		super.setUserVisibleHint(isVisibleToUser);
		// 每次切换fragment时调用的方法
		if (isVisibleToUser) {
			getDatas();
		}
	}

	DisplayImageOptions options = new DisplayImageOptions.Builder()
	.showImageForEmptyUri(R.drawable.ic_menu_rotate) // 设置图片Uri为空或是错误的时候显示的图片
	.showImageOnFail(R.drawable.ic_menu_rotate) // 设置图片加载或解码过程中发生错误显示的图片
	.resetViewBeforeLoading(false)  // default 设置图片在加载前是否重置、复位
	.delayBeforeLoading(0)  // 下载前的延迟时间
	.cacheInMemory(false) // default  设置下载的图片是否缓存在内存中
	.cacheOnDisk(true) // default  设置下载的图片是否缓存在SD卡中
	.considerExifParams(false) // default
	.imageScaleType(ImageScaleType.EXACTLY) // default 设置图片以如何的编码方式显示
	.bitmapConfig(Bitmap.Config.RGB_565) // default 设置图片的解码类型
	//		.displayer(new SimpleBitmapDisplayer()) // default  还可以设置圆角图片new RoundedBitmapDisplayer(20)
	.build();
	
	
	private void getData(){
//		if (mImageUrl.contains(AppUrl.SHOW_DOT_TAG)) {
//			mImageView.setImageBitmap(ScanCertiActivity.DOT_PIC);
//			mAttacher.update();
//			return;
//		}
		
		if(mImageUrl.indexOf("http:")==-1){
			//判断是否为本地图片
			Glide.with(ImageDetailFragment.this)
			.load(mImageUrl)
			.crossFade()

			.into(new GlideDrawableImageViewTarget(mImageView) {

				@Override
				public void onLoadStarted(Drawable placeholder) {
					// TODO Auto-generated method stub
					super.onLoadStarted(placeholder);
					VolleyBasic.showLoding(getActivity());
				}

				@Override
				public void onResourceReady(GlideDrawable drawable,
						GlideAnimation anim) {

					super.onResourceReady(drawable, anim);
					mAttacher.update();
					drawable=null;
					// 在这里添加一些图片加载完成的操作
					VolleyBasic.disMissLoding();
				}

				@Override
				public void onLoadFailed(Exception e, Drawable errorDrawable) {
					// TODO Auto-generated method stub
					super.onLoadFailed(e, errorDrawable);
					VolleyBasic.disMissLoding();
					ToastUtil.toast(getActivity(), "图片加载失败");
				}
			});
		}else{
			//加载网络图片
			String picUrl = mImageUrl;
			if (mImageUrl.contains(Cache.base)) {
				picUrl = mImageUrl
						+ "_"+(Integer.parseInt(NetUtils.getDisplayMetrics(getActivity()).get(NetUtils.DM_WIDTH)))+ "x10.png";
			}
			ImageLoader.getInstance().displayImage(picUrl
					, mImageView,options, new SimpleImageLoadingListener() {
				@Override
				public void onLoadingStarted(String imageUri, View view) {
					progressBar.setVisibility(View.VISIBLE);
				}

				@Override
				public void onLoadingFailed(String imageUri, View view,
											FailReason failReason) {
					// TODO Auto-generated method stub
					super.onLoadingFailed(imageUri, view, failReason);
					String message = null;
					switch (failReason.getType()) {
					case IO_ERROR:
						message = "下载错误";
						ToastUtil.toast(getActivity(), message);
						break;
					case DECODING_ERROR:
						message = "图片无法显示";
						ToastUtil.toast(getActivity(), message);
						break;
					case NETWORK_DENIED:
						message = "网络有问题，无法下载";
						ToastUtil.toast(getActivity(), message);
						break;
					case OUT_OF_MEMORY:
						message = "图片太大无法显示";
						ToastUtil.toast(getActivity(), message);
						break;
					case UNKNOWN:
						message = "未知的错误";
						ToastUtil.toast(getActivity(), message);
						break;
					}
					progressBar.setVisibility(View.GONE);
				}


				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap
						loadedImage) {
					progressBar.setVisibility(View.GONE);
					
					mAttacher.update();
					loadedImage=null;
					ArtToGoApp.ClearImageLoaderMemoryClick();
				}
			});

		}
	}

}
